package com.turing.selfwebservice.common;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.turing.post.webservice.client.AnyTypeArray;
import com.turing.post.webservice.client.CommonWebResult;
import com.turing.post.webservice.client.PCPSApplicationException_Exception;
import com.turing.post.webservice.client.WebWscImpl;
import com.turing.post.webservice.client.WebWscImplPortType;
import com.turing.selfwebservice.system.SessionHashTable;

public class DataMigrateServlet extends DispatchAction {

	private HttpSession session = null;
	private WebWscImplPortType webWscImplPortType = null;

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		session = request.getSession();
		getLink();
		SessionHashTable sht = (SessionHashTable) session
				.getAttribute("SessionHashTable");
		webWscImplPortType = sht.getWebservice();
		return super.execute(mapping, form, request, response);
	}

	/**
	 * 已清分数据迁移
	 */

	public ActionForward getPMBSSortInfo(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		if (webWscImplPortType == null)
			response.getWriter().write("webservice连接失败!");

		try {
			// CommonWebResult result =
			String issuecompanyno = request.getParameter("issuecompanyno");
			webWscImplPortType.sortInfoTranfer(issuecompanyno,true);
		} catch (PCPSApplicationException_Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 已清分继续迁移
	 */

	public ActionForward getPMBSSortInfoGoOn(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		if (webWscImplPortType == null)
			response.getWriter().write("webservice连接失败!");

		try {
			// CommonWebResult result =
			String issuecompanyno = request.getParameter("issuecompanyno");
			webWscImplPortType.sortInfoTranfer(issuecompanyno,false);
		} catch (PCPSApplicationException_Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 卡库存迁移
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward getEntityCardListInsertCardStock(
			ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		if (webWscImplPortType == null)
			response.getWriter().write("webservice连接失败!");
		String issuecompanyno = request.getParameter("issuecompanyno");
		for (int i = 0; i < 100; i++) {
			CardStock test = new CardStock(StrFro("02", i), issuecompanyno);
			Thread thread = new Thread(test);
			thread.start();
		}
		return null;
	}

	/**
	 * 卡库存明细迁移
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward insertIssueCardStockDetail(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		if (webWscImplPortType == null)
			response.getWriter().write("webservice连接失败!");
		String cardFaceId = request.getParameter("cardFaceId");
		String operId = request.getParameter("operId");
		List<AnyTypeArray> list = webWscImplPortType.getCardStockList();
		for (AnyTypeArray any : list) {
			List<Object> obj = any.getItem();
			CardDetail cardDetail = new CardDetail(obj.get(0).toString(), obj
					.get(1).toString(), new BigInteger(cardFaceId),
					new BigInteger(operId));
			Thread thread = new Thread(cardDetail);
			thread.start();
		}
		return null;
	}

	private void getLink() throws Exception {
		String wsdl = getDbConnection();
		if (!wsdl.equals("")) {
			URL wsdlURL = new URL(wsdl);
			QName serviceQName = new QName(
					"http://impl.webservice.post.turing.com/", "WebWscImpl");
			Service service = WebWscImpl.create(wsdlURL, serviceQName);
			WebWscImplPortType postPortType = service
					.getPort(WebWscImplPortType.class);
			SessionHashTable sht = new SessionHashTable();
			sht.setWebservice(postPortType);
			session.setAttribute("SessionHashTable", sht);
		}
	}

	private String getDbConnection() {
		InputStream is = getServlet().getServletContext().getResourceAsStream(
				"/WEB-INF/WSConn.properties");
		Properties props = new Properties();
		try {
			props.load(is);
		} catch (IOException e) {
			System.err.println("DbConnection.xml File Is Not Find!");
		}
		String res = props.getProperty("webserver_address");
		return res;
	}

	class CardStock implements Runnable {
		private String number;
		private String issueCompanyNo;

		public CardStock() {
		}

		public CardStock(String number, String issueCompanyNo) {
			this.number = number;
			this.issueCompanyNo = issueCompanyNo;
		}

		public void run() {
			try {
				// CommonWebResult result =
				webWscImplPortType.getEntityCardListInsertCardStock(number,
						issueCompanyNo);
			} catch (PCPSApplicationException_Exception e) {
				e.printStackTrace();
			}
		}
	}

	class CardDetail implements Runnable {

		private String issueBranchNo;
		private String batchNo;
		private BigInteger cardFaceId;
		private BigInteger operId;

		public CardDetail() {
		}

		public CardDetail(String issueBranchNo, String batchNo,
				BigInteger cardFaceId, BigInteger operId) {
			this.issueBranchNo = issueBranchNo;
			this.batchNo = batchNo;
			this.cardFaceId = cardFaceId;
			this.operId = operId;
		}

		public void run() {
			try {
				// CommonWebResult result =
				webWscImplPortType.insertIssueCardStockDetail(issueBranchNo,
						batchNo, cardFaceId, operId);
			} catch (PCPSApplicationException_Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 数字不够位数前面补0
	 * 
	 * @param num
	 * @param no
	 * @return
	 */
	private static String StrFro(String num, Integer no) {
		return String.format("%" + num + "d", no);
	}

	// 发卡机构迁移
	public ActionForward getIssueBranch(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (webWscImplPortType == null)
			response.getWriter().write("webservice连接失败!");
		String issuecompanyno = request.getParameter("issuecompanyno");
		String regionNo = request.getParameter("regionNo");

		CommonWebResult result = webWscImplPortType.insertNewIssueBranch(null,
				issuecompanyno, regionNo);
		if (result.isSuccess() == true) {
			response.getWriter().write("迁移成功!");
		} else {
			response.getWriter().write(result.getExcepMessage());
		}
		return null;
	}

	// 销售机构迁移
	public ActionForward getSaleBranch(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (webWscImplPortType == null)
			response.getWriter().write("webservice连接失败!");
		String issuecompanyno = request.getParameter("issuecompanyno");
		String regionNo = request.getParameter("regionNo");
		String incomeBranchId = request.getParameter("incomeBranchId");
		String issuebranchno = request.getParameter("issuebranchno");

		CommonWebResult result = webWscImplPortType.insertNewSaleBranch(null,
				issuecompanyno, regionNo, issuebranchno, incomeBranchId);
		if (result.isSuccess() == true) {
			response.getWriter().write("迁移成功!");
		} else {
			response.getWriter().write(result.getExcepMessage());
		}
		return null;
	}

	// 用户迁移
	public ActionForward getUser(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (webWscImplPortType == null)
			response.getWriter().write("webservice连接失败!");
		String issuecompanyno = request.getParameter("issuecompanyno");
		String roleid = request.getParameter("roleid");
		String issuebranchno = request.getParameter("issuebranchno");
		CommonWebResult result = webWscImplPortType.insertNewUser(null,
				issuebranchno, issuecompanyno, roleid);
		if (result.isSuccess() == true) {
			response.getWriter().write("迁移成功!");
		} else {
			response.getWriter().write(result.getExcepMessage());
		}
		return null;
	}

	// 商户迁移
	public ActionForward getMerchant(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (webWscImplPortType == null)
			response.getWriter().write("webservice连接失败!");
		String issuecompanyno = request.getParameter("issuecompanyno");
		String issuebranchno = request.getParameter("issuebranchno");
		String incomeBranchId = request.getParameter("incomeBranchId");
		String regionNo = request.getParameter("regionNo");

		CommonWebResult result = webWscImplPortType.insertNewMerchant(null,
				issuecompanyno, regionNo, issuebranchno, incomeBranchId);
		if (result.isSuccess() == true) {
			response.getWriter().write("迁移成功!");
		} else {
			response.getWriter().write(result.getExcepMessage());
		}
		return null;
	}

	// 卡种类迁移
	public ActionForward getCardClass(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (webWscImplPortType == null)
			response.getWriter().write("webservice连接失败!");
		String issuecompanyno = request.getParameter("issuecompanyno");
		CommonWebResult result = webWscImplPortType
				.insertCardClassic(issuecompanyno);
		if (result.isSuccess() == true) {
			response.getWriter().write("迁移成功!");
		} else {
			response.getWriter().write(result.getExcepMessage());
		}
		return null;
	}

	// 卡控制迁移
	public ActionForward getMakeCard(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (webWscImplPortType == null)
			response.getWriter().write("webservice连接失败!");
		String issuecompanyno = request.getParameter("issuecompanyno");
		String cardManufactureId = request.getParameter("cardManufactureId");
		String cardFaceId = request.getParameter("cardFaceId");
		CommonWebResult result = webWscImplPortType.insertMakeCardControl(
				issuecompanyno, cardManufactureId, cardFaceId);
		if (result.isSuccess() == true) {
			response.getWriter().write("迁移成功!");
		} else {
			response.getWriter().write(result.getExcepMessage());
		}
		return null;
	}

	class PMBSHisTradDetail implements Runnable {
		private int number;
		private int xiancheng;

		public PMBSHisTradDetail() {
		}

		public PMBSHisTradDetail(int xiancheng, int number) {
			this.xiancheng = xiancheng;
			this.number = number;
		}

		public void run() {
			try {
				List<AnyTypeArray> objList = webWscImplPortType
						.getMchTradDetailTranDateList();
				List<Object> objs = null;
				int fors = objList.size() / xiancheng;// 循环数
				int a = number * fors;
				int b = a + fors;
				for (int i = a; i <= b; i++) {
					objs = objList.get(i).getItem();
					webWscImplPortType.transferPMBSMchTradDetail("", objs
							.get(0).toString());
				}

			} catch (PCPSApplicationException_Exception e) {
				e.printStackTrace();
			}
		}
	}

	// PMBS 已迁移数据map删除
	public ActionForward deleteMapTradDetail(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		if (webWscImplPortType == null)
			response.getWriter().write("webservice连接失败!");
		webWscImplPortType.deleteMapPMBSTradDetail();
		return null;
	}

	// PMBS流水迁移
	public ActionForward getPMBSHisTradDetail(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		if (webWscImplPortType == null)
			response.getWriter().write("webservice连接失败!");
		// 线程数量50
		int xiancheng = 50;
		for (int i = 0; i < xiancheng; i++) {
			PMBSHisTradDetail test = new PMBSHisTradDetail(xiancheng, i);
			Thread thread = new Thread(test);
			thread.start();
		}
		// 余数
		List<AnyTypeArray> objList = webWscImplPortType
				.getMchTradDetailTranDateList();
		List<Object> objs = null;
		int yushu = objList.size() % xiancheng;
		int fors = objList.size() / xiancheng;// 循环数
		int a = xiancheng * fors;
		int b = a + yushu;
		for (int i = a; i < b; i++) {
			objs = objList.get(i).getItem();
			webWscImplPortType.transferPMBSMchTradDetail("", objs.get(0)
					.toString());
		}
		return null;
	}

	class PMBSTradSummary implements Runnable {
		private int number;
		private int xiancheng;

		public PMBSTradSummary() {
		}

		public PMBSTradSummary(int xiancheng, int number) {
			this.xiancheng = xiancheng;
			this.number = number;
		}

		public void run() {
			try {
				List<AnyTypeArray> objList = webWscImplPortType
						.getMchTradDetailTranDateList();
				List<Object> objs = null;
				int fors = objList.size() / xiancheng;// 循环数
				int a = number * fors;
				int b = a + fors;
				for (int i = a; i <= b; i++) {
					objs = objList.get(i).getItem();
					webWscImplPortType.transferPMBSMchAddTradSummary(objs
							.get(0).toString());
				}
			} catch (PCPSApplicationException_Exception e) {
				e.printStackTrace();
			}
		}
	}

	public ActionForward getPMBSTradSummary(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		if (webWscImplPortType == null)
			response.getWriter().write("webservice连接失败!");
		System.out.println("START : transferPMBSMchAddTradSummary");
		// 线程数量50
		int xiancheng = 50;
		for (int i = 0; i < xiancheng; i++) {
			PMBSTradSummary test = new PMBSTradSummary(xiancheng, i);
			Thread thread = new Thread(test);
			thread.start();
		}
		// 余数
		List<AnyTypeArray> objList = webWscImplPortType
				.getMchTradDetailTranDateList();
		List<Object> objs = null;
		int yushu = objList.size() % xiancheng;
		int fors = objList.size() / xiancheng;// 循环数
		int a = xiancheng * fors;
		int b = a + yushu;
		for (int i = a; i < b; i++) {
			objs = objList.get(i).getItem();
			webWscImplPortType.transferPMBSMchAddTradSummary(objs.get(0)
					.toString());
		}
		return null;
	}

	// 数据并行 PMBS交易数据
	public ActionForward getPMBSDataByTranDate(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		if (webWscImplPortType == null)
			response.getWriter().write("webservice连接失败!");
		String issuecompanyno = request.getParameter("issuecompanyno");
		String ip = request.getParameter("ip");
		String port = request.getParameter("port");
		String trandate = request.getParameter("trandate");
		String oldMerchantNo = request.getParameter("oldMerchantNo");
		String tag = request.getParameter("tag");
		CommonWebResult result = null;
		if ("0".equals(tag)) {
			result = webWscImplPortType.tranferPMBSDataByTranDate(
					issuecompanyno, ip, Integer.parseInt(port), trandate,
					oldMerchantNo, true);
		} else if ("1".equals(tag)) {
			result = webWscImplPortType.tranferPMBSDataByTranDate(
					issuecompanyno, ip, Integer.parseInt(port), trandate,
					oldMerchantNo, false);
		}
		if (result.isSuccess() == true) {
			response.getWriter().write("数据处理成功!");
		} else {
			response.getWriter().write(result.getExcepMessage());
		}
		return null;
	}

	// 数据并行 CARD便民驿站交易数据
	public ActionForward getPIBSDataByTranDate(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		if (webWscImplPortType == null)
			response.getWriter().write("webservice连接失败!");
		String ip = request.getParameter("ip");
		String port = request.getParameter("port");
		String trandate = request.getParameter("trandate");
		String MerchantNo = request.getParameter("MerchantNo");
		String factMerchantNo = request.getParameter("factMerchantNo");
		String webMerchantNo = request.getParameter("webMerchantNo");

		List<AnyTypeArray> objsList = webWscImplPortType
				.getCardManagerBranchNoList(trandate);
		String branchNo = "";
		Integer po = Integer.parseInt(port);
		int xiancheng = objsList.size();
		for (int i = 0; i < xiancheng; i++) { 
			AnyTypeArray ata = objsList.get(i);
			branchNo = ata.getItem().get(0).toString();
			PIBSTradDetail test = new PIBSTradDetail(branchNo, ip, po,
					trandate, MerchantNo, factMerchantNo, webMerchantNo);
			Thread thread = new Thread(test);
			thread.start();
		}
		return null;
	}

	class PIBSTradDetail implements Runnable {
		private String branchNo;
		private String ip;
		private Integer port;
		private String trandate;
		private String MerchantNo;
		private String factMerchantNo;
		private String webMerchantNo;

		public PIBSTradDetail() {
		}

		public PIBSTradDetail(String branchNo, String ip, Integer port,
				String trandate, String MerchantNo, String factMerchantNo,
				String webMerchantNo) {
			this.branchNo = branchNo;
			this.ip = ip;
			this.port = port;
			this.trandate = trandate;
			this.MerchantNo = MerchantNo;
			this.factMerchantNo = factMerchantNo;
			this.webMerchantNo = webMerchantNo;
		}

		public void run() {
			webWscImplPortType.tranferPIBSDataByTranDate(branchNo, ip, port,
					trandate, MerchantNo, factMerchantNo, webMerchantNo);
		}
	}

	/**
	 * 激活卡---数据迁移
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward tranferActivateCard(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		if (webWscImplPortType == null)
			response.getWriter().write("webservice连接失败!");
		try {
			String issuecompanyno = request.getParameter("issuecompanyno");
			String threadcntstr = request.getParameter("threadcnt");

			List<AnyTypeArray> list = webWscImplPortType
					.getBatchNoFromOldActivateCard();
			System.out.println("总共有批次号:" + list.size());
			Map<Integer, ArrayList<String>> batchlist = new HashMap<Integer, ArrayList<String>>();
			int threadcnt = 71;
			if (threadcntstr != null) {
				threadcnt = Integer.valueOf(threadcnt);
			}
			for (AnyTypeArray any : list) {
				List<Object> obj = any.getItem();
				Integer thrid = Integer.parseInt(obj.get(0).toString())
						% threadcnt;
				ArrayList<String> o = batchlist.remove(thrid);
				if (o == null)
					o = new ArrayList<String>();
				o.add(obj.get(0).toString());
				batchlist.put(thrid, o);
			}
			CountDownLatch runningThreadNum = new CountDownLatch(batchlist
					.size());
			for (Map.Entry<Integer, ArrayList<String>> entry : batchlist
					.entrySet()) {
				ActivateCard ac = new ActivateCard(issuecompanyno, entry
						.getValue());
				Thread thread = new Thread(ac);
				thread.start();
			}
			runningThreadNum.await();
			System.out.println("ALL PROCESS END!!!! ");
		} catch (Exception e) {
			request.setAttribute("Error",
					"webservice连接异常，检查webservice是否启动或网络连通!");
			response.getWriter().write("webservice连接异常，检查webservice是否启动或网络连通!");
		}
		response.getWriter().write("激活卡迁移线程启动成功....");
		return null;
	}

	/**
	 * 激活卡迁移内部类
	 * 
	 * @author kangzhe
	 * 
	 */
	class ActivateCard implements Runnable {
		private String issueCompanyNo;
		private List<String> batchNoList;

		public ActivateCard() {
		}

		public ActivateCard(String issueCompanyNo, List<String> batchNoList) {
			this.issueCompanyNo = issueCompanyNo;
			this.batchNoList = batchNoList;
		}

		public void run() {
			try {
				for (String batchNo : batchNoList) {
					System.out.println("BEGIN: " + batchNo);
					webWscImplPortType.tranferActivateCard(issueCompanyNo,
							batchNo);
					System.out.println("END: " + batchNo);
				}
			} catch (PCPSApplicationException_Exception e) {
				e.printStackTrace();
			}
		}
	}

	// 自动售卡
	public ActionForward saleOldCard(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (webWscImplPortType == null)
			response.getWriter().write("webservice连接失败!");
		String icNo = request.getParameter("issuecompanyno");
		String startDate = request.getParameter("trandate");
		String endDate = request.getParameter("enddate");
		String userid = request.getParameter("operId");
		String faceid = request.getParameter("cardFaceId");

		CommonWebResult result = webWscImplPortType.saleOldCard(icNo,
				startDate, endDate, new BigInteger(userid), new BigInteger(
						faceid));
		if (result.isSuccess() == true) {
			response.getWriter().write("数据处理成功!");
		} else {
			response.getWriter().write(result.getExcepMessage());
		}
		return null;
	}
}
